﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NewServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建一个Socket负责通信
                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // 获取ip地址和端口号
                IPAddress iP = IPAddress.Any;
                IPEndPoint iPEndPoint = new IPEndPoint(iP, int.Parse(txtServerPort.Text));
                // 绑定监听端口
                socketWatch.Bind(iPEndPoint);
                // 限制排队
                socketWatch.Listen(10);
                ShowMsg("开始监听...");
                // 用线程去执行Socket 来获取客户端连接
                Thread th = new Thread(Listen);
                th.IsBackground = true;
                th.Start(socketWatch);
            }
            catch { }
        }

        // 用于存放客户端的信息
        Dictionary<string, Socket> keyValuePairs = new Dictionary<string, Socket>();
        /// <summary>
        /// 获取客户端的连接
        /// </summary>
        /// <param name="o"></param>
        Socket socketSend;
        public void Listen(object o)
        {
            Socket socketWatch = o as Socket;
            // 负责通信的Socket
            while (true)
            {
                try
                {
                    socketSend = socketWatch.Accept();
                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ":连接成功");
                    // 将连接的ip放在listbox集合中
                    cboIps.Items.Add(socketSend.RemoteEndPoint.ToString());
                    keyValuePairs.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                    // 用线程去执行Socket 来获取客户端信息
                    Thread th = new Thread(Receive);
                    th.IsBackground = true;
                    th.Start(socketSend);
                }
                catch { }
            }
        }

        /// <summary>
        /// 用来接受客户端发来的消息
        /// </summary>
        /// <param name="o"></param>
        public void Receive(object o)
        {
            Socket socketWatch = o as Socket;
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    int r = socketWatch.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, r);
                    ShowMsg(socketWatch.RemoteEndPoint + ":" + str);
                }
                catch { }
            }
        }

        public void ShowMsg(string str)
        {
            txtAcceptMsg.AppendText(str + "\r\n");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 给客户端发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] buffer = Encoding.UTF8.GetBytes(txtMsgs.Text);
                List<byte> list = new List<byte>();
                list.Add(0);
                list.AddRange(buffer);
                keyValuePairs[cboIps.Text].Send(list.ToArray());
                //socketSend.Send(buffer);
            }
            catch { }
        }

        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChoseFIle_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "请选择文件";
            openFileDialog.Filter = "文本文件|*.txt|所有文件|*.*";
            openFileDialog.InitialDirectory = @"C:\Users\CC\Desktop";
            openFileDialog.ShowDialog();
            txtFIlePath.Text = openFileDialog.FileName;
        }

        /// <summary>
        /// 发送文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSendFile_Click(object sender, EventArgs e)
        {
            try
            {
                using (FileStream fileStream = new FileStream(txtFIlePath.Text, FileMode.Open, FileAccess.Read))
                {
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    int r = fileStream.Read(buffer, 0, buffer.Length);
                    List<byte> list = new List<byte>();
                    list.Add(1);
                    list.AddRange(buffer);
                    byte[] newBuffer = list.ToArray();
                    keyValuePairs[cboIps.Text].Send(newBuffer, 0, r + 1, SocketFlags.None);
                }
            }
            catch { }
        }

        /// <summary>
        /// 使客户端震动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnZD_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] buffer = new byte[1];
                buffer[0] = 2;
                keyValuePairs[cboIps.Text].Send(buffer);
            }
            catch { }
        }
    }
}
